import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listUserApi, registerUserApi } from '@/api/user'
import { handleApiError, handleSuccess } from '@/utils/errorUtils'

export const useUserListStore = defineStore('userList', () => {
  // ==================== 状态定义 ====================
  const userList = ref([])
  const total = ref(0)
  const loading = ref(false)
  
  const queryParams = ref({ 
    page: 1, 
    limit: 10 
  })

  // ==================== API调用方法 ====================
  const loadUserList = async () => {
    try {
      loading.value = true
      const res = await listUserApi({ 
        page: queryParams.value.page, 
        limit: queryParams.value.limit 
      })
      userList.value = res.data?.list || res.list || []
      total.value = res.data?.total || res.total || 0
    } catch (error) {
      handleApiError(error, '获取用户列表失败')
    } finally {
      loading.value = false
    }
  }

  const registerUser = async (data) => {
    try {
      await registerUserApi(data)
      handleSuccess('注册成功')
      await loadUserList()
    } catch (error) {
      handleApiError(error, '注册失败')
    }
  }

  // ==================== 业务逻辑方法 ====================
  const updateQueryParams = (params) => {
    queryParams.value = { ...queryParams.value, ...params }
  }

  const resetQueryParams = () => {
    queryParams.value = { page: 1, limit: 10 }
  }

  // ==================== 返回状态和方法 ====================
  return {
    // 状态
    userList,
    total,
    loading,
    queryParams,
    
    // API方法
    loadUserList,
    registerUser,
    
    // 业务方法
    updateQueryParams,
    resetQueryParams
  }
})